<template>
  <div style="margin-top: 50px">
    <el-form :model="vulue" :rules="rules" ref="productBaseForm" label-width="120px" style="width: 600px" size="small">
      <el-form-item label="商品名称" prop="name">
            <el-input placeholder="请输入商品名称" v-model="vulue.name"></el-input>
        </el-form-item>
        <el-form-item label="短标题" prop="simpleTitle">
            <el-input placeholder="请输入短标题" v-model="vulue.simpleTitle"></el-input>
        </el-form-item>
        <el-form-item label="长标题" prop="title">
            <el-input placeholder="请输入长标题" v-model="vulue.title"></el-input>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload class="avatar-uploader" :limit="maxLimitNum" name="imageFile" list-type="picture-card" :disabled="isDisabled" :auto-upload="true"
            :headers="requestHeader" :action="uploadImgUrl" :show-file-list="true" :on-success="handleAvatarSuccess" :on-remove="handleRemove"
            :before-upload="beforeAvatarUpload" :data="uploadParam" accept="image/jpeg,image/png"
            :file-list="uploadFileList">
            <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar"> -->
            <i class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
        </el-form-item>
        <el-form-item label="店铺" prop="shopId">
            <el-select class="filter-item" v-model="vulue.shopId" placeholder="请选择店铺" @change="shopChange">
              <el-option v-for="item in  shopOptions" :key="item.shopId" :label="item.shopName" :value="item.shopId"> </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="mkCategoryCode">
            <el-cascader :options="categoryOptions" ref="goodCate" @change="onCategoryChange" :show-all-levels="false" change-on-select v-model="categoryCode" value="code" :props="cateProps"></el-cascader>
        </el-form-item>
        <el-form-item label="付款方式" prop="onlyPayMethod">
            <el-select class="filter-item" v-model="vulue.onlyPayMethod" placeholder="请选择付款方式">
              <el-option v-for="item in  payMethodOptions" :key="item.picklistValue" :label="item.picklistText" :value="item.picklistValue"> </el-option>
            </el-select>
        </el-form-item>        
        <el-form-item label="原价（元）" prop="oringinalPrice">
            <el-input placeholder="请输入原价" v-model.number="vulue.oringinalPrice"></el-input>
        </el-form-item>
        <el-form-item label="现价（元）" prop="currentPrice">
            <el-input placeholder="请输入现价" v-model.number="vulue.currentPrice"></el-input>
        </el-form-item>
      <el-form-item style="text-align: center">
        <el-button type="primary" size="medium" @click="handleNext('productBaseForm')">下一步，填写商品详情</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {getObj,putObj} from 'api/shop/goods/goods/index';
  import {getPicklist} from 'api/param/picklist/index';
  import {getAllShopList} from 'api/shop/shops/index';
  import { getToken } from 'utils/auth';
  import { fetchTree } from 'api/shop/goods/category/index';
  import { mapGetters } from 'vuex';

  export default {
    name: "ProductBaseDetail",
    props: {
      vulue: Object,
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        hasEditCreated:false,
        uploadImgUrl: this.GLOBAL.uploadImgUrl,
        uploadParam:{"useType":"goods"},
        shopOptions:[],
        maxLimitNum:6,
        isDisabled:false,
        categoryOptions:[],
        categoryCode:[],
        imageUrl:'',
        imgs:[],
        requestHeader:{"token":getToken()},
        uploadFileList:[],
        payMethodOptions:[
          {"picklistValue":"0","picklistText":"不限制"},
          {"picklistValue":"1","picklistText":"在线支付"},
          {"picklistValue":"2","picklistText":"到店支付"},
          {"picklistValue":"3","picklistText":"货到付款"},
        ],
        cateProps:{
          value: 'code',
          label:'name',
        },
        rules: {
          name: [
            {required: true, message: '请输入商品名称', trigger: 'blur'},
            {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
          ],
          simpleTitle: [{required: true, message: '请输入商品短标题', trigger: 'blur'}],
          title: [{required: true, message: '请输入商品长标题', trigger: 'blur'}],
          shopId: [{required: true, message: '请选择店铺', trigger: 'blur'}],
          mkCategoryCode: [{required: true, message: '请选择商品分类', trigger: 'blur'}],
          onlyPayMethod: [{required: true, message: '请输入商品付款方式', trigger: 'blur'}],
          oringinalPrice: [
            {type: 'number',required: true,message: '请输入现价', trigger: 'blur'},
            {validator:(rule,value,callback)=>{
                if(value != ""){
                  if((/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/).test(value) == false || typeof value !== 'number'){
                  callback(new Error("请填写大于0的数字"));
                  }else{
                  callback();
                  }
                }else{
                  callback();
                }
              },
              trigger: 'blur'
            }
          ],
          currentPrice: [
            {type: 'number',required: true,message: '请输入现价',trigger: 'blur'},
            {validator:(rule,value,callback)=>{
                if(value != ""){
                  if((/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/).test(value) == false || typeof value !== 'number'){
                  callback(new Error("请填写大于0的数字"));
                  }else{
                  callback();
                  }
                }else{
                  callback();
                }
              },
              trigger: 'blur'
            }
          ],
        }
      };
    },
    created() {
      this.getAllShopList();
    },
    computed:{
    },
    watch: {
    },
    methods: {
      getAllShopList() {
        getAllShopList()
          .then(response => {
            this.shopOptions = response.data;
          })
      },
      shopChange(event,item){
        var shopId = event;
        this.getCategoryList(shopId);
      },
      getCategoryList(shopId){
        this.listQuery.shopId = shopId;
        fetchTree(this.listQuery).then(data => {
          this.categoryOptions = data;
        });
      },
      handleAvatarSuccess(res, file, fileList) {
        this.uploadFileList = fileList;
        --this.maxLimitNum;
        if(this.maxLimitNum <= 0) this.isDisabled = true;
        this.imgs.push(res.data);
      },
      beforeAvatarUpload(file) {
        const isJPG = (file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png');
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG || !file.type) {
          this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return (isJPG) && isLt2M;
      },
      handleRemove(file, fileList){
        if(file != null){
        var fileName = file.response.data;
        var index = this.imgs.indexOf(fileName);
        if (index > -1) {
            this.imgs.splice(index, 1);
        }
        this.maxLimitNum++;
        this.isDisabled = false;
        }
      },
      onCategoryChange(item){
        // console.log(item, this.$refs['goodCate'].currentLabels)
        var labels = this.$refs['goodCate'].currentLabels;
        this.vulue.mkCategoryCode = item[item.length - 1]
        this.vulue.categoryName = labels[labels.length - 1]
      },
      handleNext(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$emit('nextStep');
          } else {
            this.$message({
              message: '验证失败',
              type: 'error',
              duration:1000
            });
            return false;
          }
        });
      }
    }
  }
</script>

<style scoped>
</style>